import os
import subprocess
import argparse

def check_code_quality(path, report_file=None):
    if not os.path.exists(path):
        print(f"路径不存在: {path}")
        return

    if os.path.isfile(path):
        # 如果是文件，直接检查该文件
        result = subprocess.run(['pylint', path], capture_output=True, text=True)
        if report_file:
            with open(report_file, 'w') as f:
                f.write(result.stdout)
        else:
            print(result.stdout)
    elif os.path.isdir(path):
        # 如果是文件夹，检查该文件夹中的所有 Python 文件
        python_files = [f for f in os.listdir(path) if f.endswith('.py')]
        if not python_files:
            print(f"文件夹中没有 Python 文件: {path}")
            return
        for file in python_files:
            file_path = os.path.join(path, file)
            print(f"检查文件: {file_path}")
            result = subprocess.run(['pylint', file_path], capture_output=True, text=True)
            if report_file:
                with open(report_file, 'a') as f:
                    f.write(result.stdout)
            else:
                print(result.stdout)
    else:
        print("请提供有效的文件或文件夹路径。")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='检查代码质量')
    parser.add_argument('path', help='文件或文件夹路径')
    parser.add_argument('--report', help='输出报告的文件路径')
    args = parser.parse_args()

    check_code_quality(args.path, args.report)